#import "PushPlugin.h"
#import "BPush.h"

@implementation PushPlugin

CDVPlugin *globallugin = nil;
NSString *callBackId= nil;
NSString *chanelId = nil;

BOOL enableNotify = true;



-(void) init:(CDVInvokedUrlCommand*)command{
    globallugin = self;
    callBackId = command.callbackId;
}

-(void) setTag:(CDVInvokedUrlCommand *)command{
    NSArray *arguments= command.arguments;
    NSString *tag = arguments[0];
    [BPush setTag:tag withCompleteHandler:^(id result, NSError *error) {
        if (result) {
             NSLog(@"设置tag成功");
             [self sendPluginResult:command rtnResult:@"ok"];
        }else{
            NSLog(@"设置tag失败");
            [self sendPluginResult:command rtnResult:@"error"];
        }
    }];
   
}


-(void) startWork:(CDVInvokedUrlCommand *)command{
    if(enableNotify){
        [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
            // 需要在绑定成功后进行 settag listtag deletetag unbind 操作否则会失败
            if (result) {
                chanelId  = [result valueForKey:@"channel_id"];
                NSLog(@"绑定成功");
                [self sendPluginResult:command rtnResult:chanelId];
                return;
            }
            else{
                NSLog(@"绑定失败");
                [self sendPluginResult:command rtnResult:@"error"];
                return;
            }
        }];
        [self sendPluginResult:command rtnResult:@"error"];
    }
    else{
        [self sendPluginResult:command rtnResult:@"error"];
    }
}

-(void) stopWork:(CDVInvokedUrlCommand *)command{
    [BPush unbindChannelWithCompleteHandler:^(id result, NSError *error) {
        if(result){
            NSLog(@"停止工作成功");
            [self sendPluginResult:command rtnResult:@"ok"];
        }
        else{
             NSLog(@"停止工作失败");
            [self sendPluginResult:command rtnResult:@"error"];
        }
    }];
    
}


- (void)sendPluginResult:(CDVInvokedUrlCommand *)command rtnResult:(NSString *)msg{
    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:msg];
    [result setKeepCallback:([NSNumber numberWithBool:YES])];
    
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

- (void)test:(CDVInvokedUrlCommand *)command{
    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"test"];
    [result setKeepCallback:([NSNumber numberWithBool:YES])];
    [globallugin.commandDelegate sendPluginResult:result callbackId:callBackId];
}

@end


